import React, { Component } from 'react';
import { connect } from 'dva';
import {Button,Form,Select,Input,Radio,message,Cascader} from 'antd';
import './less/report.less';
import Drawer from 'react-motion-drawer';

import { getDictInformation,getDistrictData,savePerShareholder,comStockGetShareholderById } from "../../../services/api";
import PSelect from "../../../components/Pro/PSelect";

const FormItem = Form.Item;
const {Option} = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
let addZiShareolderIdLocal = '';


@connect(state => ({profile: state.profile}))
@Form.create()

export default class AddZiShareloder extends Component {
  constructor(props,context){
    super(props,context);
    console.log("prop:",this);
    this.state = {
      loading: false,
      openAddZiShareolder:this.props.visiable,//新增机构股东
      addZiShareolderId:0,
      initUpd:0,
      nationality:[],
      nation:[],
      selectedIdCardType:'',
      selectedNationality:'CHN',
      initAdd:0,
      shareholderInfo:{
        name:'',//姓名
        phone:'',//手机
        nationality:'',//国籍
        nation:'',//名族
        sex:'',//性别
        houseReg:'',//户籍
        idCardType:'',//证件类型
        cerNo:'',//证件号码
        address:'',//具体地址
        areas:[] //省市区
      },
      // comId:1, //默认企业为1
      areas:[] //省市区
    };
  }

  componentWillReceiveProps(props){
    if(props.visiable){
      this.setState({openAddZiShareolder:props.visiable});
      this.setState({addZiShareolderId:props.addZiShareolderId},()=>{
        if(this.state.addZiShareolderId !== 0 && this.state.addZiShareolderId !== undefined ){
          console.log("进入自然人修改", addZiShareolderIdLocal,props.addZiShareolderId);
          if(addZiShareolderIdLocal !== props.idx){ //编辑时，输入任何数据都会重复的执行，用此方法保证不会重复执行
            comStockGetShareholderById({id:this.state.addZiShareolderId}).then((data)=>{
              data.data.areas = [data.data.province, data.data.city, data.data.area];
              console.log('获取单个股东信息',data.data);
              this.setState({
                shareholderInfo:{
                  name: data.data.name,//姓名
                  phone: data.data.phone,//手机
                  nationality: data.data.nationality,//国籍
                  nation: data.data.nation,//名族
                  sex: data.data.sex,//性别
                  houseReg: data.data.houseReg,//户籍
                  idCardType: data.data.idCardType,//证件类型
                  cerNo: data.data.cerNo,//证件号码
                  address: data.data.address,//具体地址
                  areas: data.data.areas //省市区
                }
              });
              this.props.form.setFieldsValue(this.state.shareholderInfo);
            });
            addZiShareolderIdLocal = props.idx;
          }
        } else {
          console.log("进入自然人新增");
          if(this.state.initAdd === 0){
            this.props.form.setFieldsValue({
              name:'',//姓名
              phone:'',//手机
              nationality:'',//国籍
              nation:'',//名族
              sex:'',//性别
              houseReg:'',//户籍
              idCardType:'',//证件类型
              cerNo:'',//证件号码
              areas:[],
              address:'',//具体地址
            });
            this.setState({ initAdd:1});
          }
        }
        console.log("state:" + this.state.initAdd);
      });
    }
  }

  componentDidMount() {
    this.getDistrict();
    this.getDict();
  }

  getDict = () => {
    //字典下拉
    getDictInformation({codeTypes:
      'nationality,nation'
    }).then((data) => {
      if (data.data) {
        this.setState({
          nationality: data.data.nationality, //国籍
          nation: data.data.nation
        });
      }
    });
  };

  //省市区
  getDistrict = () => {
    getDistrictData().then((data) => {
      let areas = data.data.map((val) => {
          return {
            value: val.regionId,
            label: val.regionName,
            children:val.childs.map((valChild) => {
              return {
                value: valChild.regionId,
                label: valChild.regionName,
                children:valChild.childs.map((valChildChild) => {
                  return {
                    value: valChildChild.regionId,
                    label: valChildChild.regionName,
                  }
                })
              }
            })
          };
        }
      );
      this.setState({
        areas: areas,
      });
    })
  };

  handleSubmitShareolder = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if(!err){
        values.province = values.areas[0];
        values.city = values.areas[1];
        values.area = values.areas[2];
        // values.comId = this.state.comId;
        if (this.state.addZiShareolderId !== 0) {
          values.shareholderId = this.state.addZiShareolderId;
        }

        console.log('提交的内容：',values);
        this.setState({ loading: true});
        savePerShareholder({...values}).then((data) => {
          // message.success('提交成功！');
          this.props.forceUpdate();
          this.setState({
            openAddZiShareolder:false,
            loading:false
          });
          if (this.state.addZiShareolderId === 0) {
            this.setState({ initAdd:0});
          }
        });
        delete values.areas;
      }else{
        message.error('提交失败！');
        this.setState({ loading: false});
      }
    })
  };

   //验证手机号码
   checkPhone = (rule, value, callback) => {
    if (value && !(/^1[0-9]{10}$/).test(value)) {
      callback('请输入正确的手机号码！');
    } else {
      callback();
    }
  };

  //证件类型-号码验证-身份证
  checkIdCardNo = (rule, value, callback) => {
    // const form = this.props.form;
    // const idType = form.getFieldValue('idCardType');
    // console.log('证件类型select发生变化的值:' + idType);
    if (value && !(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/).test(value)) {
      callback('请输入正确的身份证号码！');
    } else{
      callback();
    }
  };

  //证件类型-号码验证-其他
  checkCardNo = (rule, value, callback) => {
    if ((value && !(/^[A-Za-z0-9]{1,20}$/).test(value))) {
      callback('请输入最大20位长度的证件号码！');
    } else {
      callback();
    }
  };


  //验证名称类，限制不能全角输入
  checkFullWidth = (rule, value, callback) => {
    if (value && !(/[^\uFF00-\uFFFF]/g).test(value)) {
      callback('请输入正确的名称！');
    } else {
      callback();
    }
  };

  //身份证改变事件
  idCardTypeOnChangeHandler = (value) =>{
      // this.props.form.validateFields(['cerNo']);
      this.props.form.setFieldsValue({'cerNo':''});
      this.setState({selectedIdCardType:value});
  };

  //国籍改变事件
  nationalityOnChangeHandler = (value) =>{
    console.log("国籍：" + value);
    this.props.form.setFieldsValue({'nation':''});
    this.setState({ shareholderInfo:{nationality: value} });
      // this.setState({});
  };

  renderNation = () => {
    return this.state.nation.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  renderNationality = () => {
    return this.state.nationality.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  render() {
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    let mark = '新增';
    if(this.state.addZiShareolderId !== 0 && this.state.addZiShareolderId !== undefined ){
      mark = '修改';
    }

    const {getFieldDecorator} = this.props.form;

    console.log(">>>>>>>>>>>>>>>>>>>>>>",this.state.shareholderInfo.nationality);
    return(
      <Drawer
        overlayColor="rgba(0, 0, 0,0)"
        right
        open={this.state.openAddZiShareolder}
        noTouchClose
        width={600}
        zIndex={2}
        className="drawer-box"
        onChange={(openAddZiShareolder) => {
          this.props.onChange(openAddZiShareolder);
          this.setState({openAddZiShareolder});
        }}
      >
        <div className="drawer">
          <div className="drawer-header">
            <h3>{mark}自然人股东</h3>
          </div>
          <div className="drawer-content" style={{marginTop:24}}>
            <Form onSubmit={this.handleSubmitShareolder}>
              <FormItem
                {...formItemLayout}
                label="姓名"
              >
                {getFieldDecorator('name', {
                  initialValue: this.state.shareholderInfo.name,
                  rules: [{
                    required: true, message: '请输入姓名',
                  },{
                    pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/,
                    message: "请输入中文最大长度20"
                  }],
                })(
                  <Input placeholder="请输入" maxLength="20"/>
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="手机号"
              >
                {getFieldDecorator('phone', {
                  initialValue: this.state.shareholderInfo.phone,
                  rules: [{
                    required: true, message: '请输入手机号',
                  }, {
                    validator: this.checkPhone
                  }],
                })(
                  <Input placeholder="请输入" maxLength="11"/>
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="国籍"
                hasFeedback
              >
                {getFieldDecorator('nationality', {
                  initialValue: this.state.shareholderInfo.nationality,
                  rules: [
                    { required: true, message: '请选择国籍!' },
                  ],
                })(
                  <Select showSearch
                    optionFilterProp="children"
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    style={{width: '100%'}}
                    onChange={this.nationalityOnChangeHandler}
                    placeholder="请选择">
                    {this.renderNationality()}
                  </Select>
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="民族"
                hasFeedback
              >
                {getFieldDecorator('nation',{
                  initialValue: this.state.shareholderInfo.nation,
                })(
                  <Select showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  style={{width: '100%'}}
                  disabled={this.state.shareholderInfo.nationality !== 'CHN' && this.state.shareholderInfo.nationality !== 'TWN'}
                  placeholder="请选择">
                  {this.renderNation()}
                </Select>
                  // <PSelect type="nation"  style={{width: '100%'}}/>
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="性别"
              >
                {getFieldDecorator('sex', {
                  initialValue: this.state.shareholderInfo.sex,
                  rules: [{
                    required: true, message: '请选择性别',
                  }],
                })(
                  <RadioGroup>
                    <Radio value="0">男</Radio>
                    <Radio value="1">女</Radio>
                  </RadioGroup>
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="户籍"
                hasFeedback
              >
                {getFieldDecorator('houseReg', {
                  initialValue: this.state.shareholderInfo.houseReg,
                  rules: [{
                    required: true, message: '请选择户籍',
                  },{
                    pattern: /^[\u4e00-\u9fa5]{1,20}$/, message: '请输汉字最大20位!',
                  }],
                })(
                  <Input placeholder="请输入" maxLength="50"/>
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="证件类型"
                hasFeedback
              >
                {getFieldDecorator('idCardType', {
                  initialValue: this.state.shareholderInfo.idCardType,
                  rules: [{
                    required: true, message: '请选择证件类型',
                  }],
                })(
                  <PSelect type="idCardType_bak" onChange={this.idCardTypeOnChangeHandler} style={{width: '100%'}}/>
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="证件号码"
              >
                { this.state.selectedIdCardType === '1' ?
                getFieldDecorator('cerNo', {
                  initialValue: this.state.shareholderInfo.cerNo,
                  rules: [{
                    required: true, message: '请输入证件号码！',
                  }, {
                    validator: this.checkIdCardNo
                  }],
                })(
                  <Input placeholder="请填写证件号码" maxLength="20"/>
                )
                :
                getFieldDecorator('cerNo', {
                  initialValue: this.state.shareholderInfo.cerNo,
                  rules: [{
                    required: true, message: '请输入证件号码！',
                  }, {
                    validator: this.checkCardNo
                  }],
                })(
                  <Input placeholder="请填写证件号码" maxLength="20"/>
                )
              }
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="注册地址"
                hasFeedback
              >
                {getFieldDecorator('areas', {
                  // initialValue: [this.state.shareholderInfo.province,this.state.shareholderInfo.city,this.state.shareholderInfo.area],
                  initialValue: this.state.shareholderInfo.areas,
                  rules: [
                    { required: true, message: '请选择注册地址!' },
                  ],
                })(
                  <Cascader options={this.state.areas} placeholder="请选择" />
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label=" "
                colon={false}
                className="wed-none"
              >
                {getFieldDecorator('address', {
                  initialValue: this.state.shareholderInfo.address,
                  rules: [{
                    required: true, message: '请填写公司注册详细地址',
                  },{
                    pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]{1,100}$/,
                    message: "请填写公司注册详细地址,中英文数字最大长度100"
                  }],
                })(
                  <TextArea rows={8} placeholder="请填写公司注册详细地址" maxLength="100"/>
                )}
              </FormItem>
            </Form>
          </div>
          <div className="drawer-footer">
            <Button onClick={()=>{
              this.setState({openAddZiShareolder:false});
              if (this.state.addZiShareolderId === 0) {
                this.setState({ initAdd:0});
              }
            }}>取消</Button>
            <Button type="primary"  htmlType="submit" onClick={this.handleSubmitShareolder} loading={this.state.loading}>保存</Button>
          </div>
        </div>
      </Drawer>
    );
  }
}


